package com.huashi.dealer.modular.controller.store.order;

import cn.dev33.satoken.annotation.SaIgnore;
import com.huashi.dealer.core.pojo.CommonResult;
import com.huashi.dealer.modular.business.order.bo.OrderSendBo;
import com.huashi.dealer.modular.business.order.param.OrderDeliveryParam;
import com.huashi.dealer.modular.business.order.param.OrderPriceUpdateParam;
import com.huashi.dealer.modular.business.order.param.OrderAuditParam;
import com.huashi.dealer.modular.business.order.service.StoreOrderService;
import com.huashi.dealer.commonEntity.Express;
import com.huashi.dealer.modular.business.order.vo.StoreOrderDetailVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.excel.EasyExcel;
import org.springframework.web.multipart.MultipartFile;

/**
 * Store端订单操作控制器
 * 对应PHP项目的订单操作功能（发货、审核、修改价格等）
 *
 * @author 谭陈强
 * @since 2025-08-15
 */
@Slf4j
@RestController
@RequestMapping("/store/order/operate")
@Tag(name = "Store端订单操作", description = "订单发货、审核、修改价格等操作接口")
public class OrderOperateController {

    @Resource
    private StoreOrderService storeOrderService;

    /**
     * 确认发货
     */
    @PostMapping("/delivery/{orderId}")
    @Operation(summary = "确认发货", description = "确认订单发货")
    public CommonResult<String> confirmDelivery(
            @Parameter(description = "订单ID") @PathVariable Long orderId,
            @Parameter(description = "发货参数") @Valid @RequestBody OrderDeliveryParam param) {
        
        try {
            log.info("确认发货，订单ID: {}, 参数: {}", orderId, param);
            storeOrderService.confirmDelivery(orderId, param);
            return CommonResult.ok("发货成功");
        } catch (Exception e) {
            log.error("确认发货失败，订单ID: {}", orderId, e);
            return CommonResult.error("发货失败：" + e.getMessage());
        }
    }

    /**
     * 修改订单价格
     */
    @PostMapping("/updatePrice/{orderId}")
    @Operation(summary = "修改订单价格", description = "修改订单的商品价格")
    public CommonResult<String> updateOrderPrice(
            @Parameter(description = "订单ID") @PathVariable Long orderId,
            @Parameter(description = "价格修改参数") @Valid @RequestBody OrderPriceUpdateParam param) {
        
        try {
            log.info("修改订单价格，订单ID: {}, 参数: {}", orderId, param);
            storeOrderService.updateOrderPrice(orderId, param);
            return CommonResult.ok("修改成功");
        } catch (Exception e) {
            log.error("修改订单价格失败，订单ID: {}", orderId, e);
            return CommonResult.error("修改失败：" + e.getMessage());
        }
    }

    /**
     * 审核订单（初审）
     */
    @PostMapping("/audit/initial")
    @Operation(summary = "审核订单（初审）", description = "对订单进行初审")
    public CommonResult<String> initialAudit(@Parameter(description = "审核参数") @Valid @RequestBody OrderAuditParam param) {
        
        try {
            storeOrderService.initialAudit(param.getOrderId(), param);
            return CommonResult.ok("初审成功");
        } catch (Exception e) {
            return CommonResult.error("初审失败：" + e.getMessage());
        }
    }

    /**
     * 审核订单（复审）
     */
    @PostMapping("/audit/final")
    @Operation(summary = "审核订单（复审）", description = "对订单进行复审")
    public CommonResult<String> finalAudit(@Parameter(description = "审核参数") @Valid @RequestBody OrderAuditParam param) {
        
        try {
            storeOrderService.finalAudit(param.getOrderId(), param);
            return CommonResult.ok("复审成功");
        } catch (Exception e) {
            return CommonResult.error("复审失败：" + e.getMessage());
        }
    }

    /**
     * 审核取消订单
     */
    @PostMapping("/audit/cancel")
    @Operation(summary = "审核取消订单", description = "审核用户取消订单的申请")
    public CommonResult<String> auditCancelOrder(
            @Parameter(description = "审核参数") @Valid @RequestBody OrderAuditParam param) {
        
        try {
            storeOrderService.auditCancelOrder(param.getOrderId(), param);
            return CommonResult.ok("审核成功");
        } catch (Exception e) {

            return CommonResult.error("审核失败：" + e.getMessage());
        }
    }

    /**
     * 批量发货
     */
    @PostMapping("/batchDelivery")
    @Operation(summary = "批量发货", description = "批量确认多个订单发货")
    public CommonResult<String> batchDelivery(@RequestParam("file")MultipartFile  file,@RequestParam("expressId")Long expressId) {
        
        try {
            storeOrderService.batchDelivery(file,expressId);
            return CommonResult.ok("批量发货成功");
        } catch (Exception e) {
            log.error("批量发货失败", e);
            return CommonResult.error("批量发货失败：" + e.getMessage());
        }
    }
    /*
     * 发货（支持全部发货和部分发货）
     */
    @PostMapping("/express")
    @Operation(summary = "发货", description = "支持全部发货和部分发货，部分发货时需要指定goodsNum参数")
    public CommonResult<String> express(@Valid @RequestBody OrderSendBo bo){
        try {
            storeOrderService.express(bo);
            return CommonResult.ok();

        } catch (Exception e) {
            return CommonResult.error("发货失败：" + e.getMessage());
        }
    }

    /**
     * 下载发货模板
     */
    @GetMapping("/downloadDeliveryTemplate")
    @Operation(summary = "下载发货模板", description = "下载发货模板Excel文件，包含订单号和物流编号表头")
    @SaIgnore
    public void downloadDeliveryTemplate(HttpServletResponse response) {
        try {
            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("发货模板", StandardCharsets.UTF_8).replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            // 创建表头数据
            List<List<String>> head = new ArrayList<>();
            List<String> head0 = new ArrayList<>();
            head0.add("订单号");
            List<String> head1 = new ArrayList<>();
            head1.add("物流编号");

            head.add(head0);
            head.add(head1);

            // 创建示例数据行（可选，可以为空模板）
            List<List<Object>> data = new ArrayList<>();
            List<Object> row1 = new ArrayList<>();
            row1.add("示例订单号001");
            row1.add("示例物流编号001");
            data.add(row1);

            // 使用EasyExcel写入数据
            EasyExcel.write(response.getOutputStream())
                    .head(head)
                    .sheet("发货模板")
                    .doWrite(data);

            log.info("发货模板下载成功");

        } catch (IOException e) {
            log.error("下载发货模板失败", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 获取物流公司列表
     */
    @GetMapping("/expressList")
    @Operation(summary = "获取物流公司列表", description = "获取所有启用的物流公司列表")
    @SaIgnore
    public CommonResult<List<Express>> getExpressList() {
        try {
            log.info("获取物流公司列表");
            List<Express> expressList = storeOrderService.getExpressList();
            return CommonResult.data(expressList);
        } catch (Exception e) {
            log.error("获取物流公司列表失败", e);
            return CommonResult.error("获取物流公司列表失败：" + e.getMessage());
        }
    }

//    /**
//     * 订单导出
//     */
//    @PostMapping("/export")
//    @Operation(summary = "订单导出", description = "导出订单数据到Excel文件")
//    public CommonResult<String> exportOrders(
//            @Parameter(description = "导出参数") @Valid @RequestBody StoreOrderListParam param) {
//
//        try {
//            log.info("导出订单数据，参数: {}", param);
//            String fileUrl = storeOrderService.exportOrders(param);
//            return CommonResult.data(fileUrl);
//        } catch (Exception e) {
//            log.error("导出订单数据失败", e);
//            return CommonResult.error("导出失败：" + e.getMessage());
//        }
//    }
}
